package com.zxy.supplier_system.server.service

import com.zxy.supplier_system.server.controller.GoodsBrandTagController
import com.zxy.supplier_system.server.entity.GoodsBrandTag
import com.zxy.supplier_system.server.entity.toIntIdAndName
import com.zxy.supplier_system.server.repository.GoodsBrandTagRepository
import com.zxy.supplier_system.server.utils.IntIdAndName
import com.zxy.supplier_system.server.utils.orElse404
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.server.ResponseStatusException

@Service
class GoodsBrandTagService(
    private val goodsBrandTagRepository: GoodsBrandTagRepository,
    private val systemServiceService: SystemServiceService
) {

    fun getAllTags(): List<IntIdAndName> {
        val currentSystemService = systemServiceService.getCurrentSystemService()
        return goodsBrandTagRepository.findBySystemService(currentSystemService)
            .map { it.toIntIdAndName() }
    }


    @Transactional
    fun createTag(createRequest: GoodsBrandTagController.CreateGoodsBrandTagRequest): Int {
        val currentSystemService = systemServiceService.getCurrentSystemService()
        
        // 检查标签名称是否已存在
        val existingTags = goodsBrandTagRepository.searchByName(createRequest.name, currentSystemService)
        if (existingTags.isNotEmpty()) {
            throw ResponseStatusException(HttpStatus.CONFLICT, "标签名称已存在")
        }
        
        val newTag = GoodsBrandTag().apply {
            name = createRequest.name
            systemService = currentSystemService
        }
        
        return goodsBrandTagRepository.save(newTag).id
    }

    @Transactional
    fun updateTag(id: Int, updateRequest: GoodsBrandTagController.UpdateGoodsBrandTagRequest){
        val currentSystemService = systemServiceService.getCurrentSystemService()
        
        val existingTag = goodsBrandTagRepository.findByIdAndSystemService(id, currentSystemService)
            .orElse404("标签未找到")
        
        // 检查新名称是否与其他标签冲突
        if (updateRequest.name != existingTag.name) {
            if (goodsBrandTagRepository.existsByNameAndSystemService(updateRequest.name,currentSystemService)) {
                throw ResponseStatusException(HttpStatus.CONFLICT)
            }
        }
        
        existingTag.name = updateRequest.name
        goodsBrandTagRepository.save(existingTag)
    }

    @Transactional
    fun deleteTag(id: Int) {
        val currentSystemService = systemServiceService.getCurrentSystemService()
        
        val tag = goodsBrandTagRepository.findByIdAndSystemService(id, currentSystemService)
            .orElse404("标签未找到")

        // 检查是否有关联的品牌
        if (tag.brands.isNotEmpty()) {
            throw ResponseStatusException(HttpStatus.BAD_REQUEST, "无法删除，该标签已关联到品牌")
        }
        
        goodsBrandTagRepository.delete(tag)
    }
    
}